import {
  Button,
  Form,
  FormItem,
  Input,
  Modal,
  Space,
  Tree,
  TypographyText
} from 'ant-design-vue'
import { defineComponent, onMounted, ref } from 'vue'

import { accountApi } from '@/apis'
import type { Permission } from '@/apis/accountTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import routes from '@/router/asyncRoutes'

import { useChangePassword, useDisable, useEdit } from './hooks'
import { useAdd } from './hooks/useAdd'

export default defineComponent({
  name: 'AccountManage',
  setup() {
    const allPermissions = ref<Permission[]>([])
    const allPermissionLength = ref<Map<number, number>>(new Map())
    const routeRoleTitleList = [] as { title: string; roles: string[] }[]
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        loading: false,
        toolbarConfig: {
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '姓名',
              field: 'realName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入姓名查找'
                }
              }
            },
            {
              title: '账号',
              field: 'userName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入账号查找'
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columns: [
          {
            type: 'seq',
            width: 50,
            title: '序号'
          },
          {
            title: '姓名',
            width: 110,
            field: 'realName'
          },
          {
            title: '账号',
            width: 110,
            field: 'userName'
          },
          {
            title: '模块权限',
            field: 'roleId',
            minWidth: 300,
            slots: {
              default: 'roleId'
            }
          },
          {
            title: '开户日期',
            width: 150,
            field: 'createTime',
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '状态',
            fixed: 'right',
            slots: {
              default: 'status'
            },
            width: 60
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 200
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await accountApi.getAccountList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)
    const rules = ref({
      realName: [
        { required: true, message: '请输入管理员姓名', trigger: 'blur' }
      ],
      userName: [
        { required: true, message: '请输入管理员账号', trigger: 'change' }
      ],
      permissions: [
        {
          type: 'array',
          required: true,
          message: '请勾选权限板块',
          trigger: 'change'
        }
      ]
    } as FormRules)
    const checkedKeys = ref<number[]>([])
    const halfCheckedKeys = ref<number[]>([])

    /** 刷新回调操作 */
    async function refresh(callback: PromiseFunc) {
      try {
        tableRef.value.showLoading()
        await callback()
        await tableRef.value.table.commitProxy('query')
      } finally {
        tableRef.value.hideLoading()
      }
    }

    /** 获取权限树 */
    async function getPermissionAll() {
      try {
        const res = await accountApi.getPermissionAll()
        replacePermissionsTitle(res)
        res.forEach(item => {
          item.sort = routes.find(
            rItem => rItem.meta.title == item.sourceName
          ).meta.sort
        })
        res.sort((a, b) => a.sort - b.sort)

        allPermissions.value = res
        allPermissionLength.value = flattenPermissionLength(res)
      } finally {
      }
    }

    /** 遍历子节点长度 */
    function flattenPermissionLength(
      a: Permission[],
      o: Map<number, number> = new Map()
    ) {
      for (const v of a) {
        if (Array.isArray(v.children)) {
          o.set(v.id, v.children.length)
          flattenPermissionLength(v.children, o)
        } else {
          o.set(v.id, 0)
        }
      }

      return o
    }

    onMounted(() => {
      convertRoutes(routes)
    })

    //后台返回的sourceName(role)对应到路由的title
    function convertRoutes(routeList) {
      routeList.forEach(item => {
        if (item.meta && item.meta.title && item.meta.roles) {
          routeRoleTitleList.push({
            title: item.meta.title,
            roles: item.meta.roles
          })
        }
        if (item.children) {
          convertRoutes(item.children)
        }
      })
    }

    function replacePermissionsTitle(permissionsList) {
      permissionsList.forEach(item => {
        const title = routeRoleTitleList.find(roItem =>
          roItem.roles.includes(item.sourceName)
        )?.title
        if (title) {
          item.sourceName = title
        }
        if (item.children) {
          replacePermissionsTitle(item.children)
        }
      })
    }

    function createItemTitleText(pList: any[]) {
      let text = ''
      if (pList) {
        pList = pList.map(item => {
          return (
            routeRoleTitleList.find(rItem => rItem.roles.includes(item))
              ?.title || item
          )
        })
        text = pList.join(',')
      }
      if (text.length > 100) {
        text = text.substring(0, 97) + '……'
      }
      return text
    }

    const { handleDisable } = useDisable({ refresh })
    const { showChange, newPassword, handleShowChange, handleChangePassword } =
      useChangePassword({ refresh })
    const {
      editFormRef,
      showEdit,
      editFormState,
      handleShowEdit,
      handleEditAccount,
      handleEditCancel
    } = useEdit({
      refresh,
      checkedKeys,
      halfCheckedKeys,
      allPermissionLength,
      formRules: rules
    })
    const {
      addFormRef,
      showAdd,
      addFormState,
      handleShowAdd,
      handleAddAccount,
      handleAddCancel
    } = useAdd({
      refresh,
      checkedKeys,
      halfCheckedKeys,
      formRules: rules
    })

    return {
      tableRef,
      tableConfig,
      showChange,
      newPassword,
      showEdit,
      showAdd,
      rules,
      addFormRef,
      addFormState,
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      editFormRef,
      editFormState,
      checkedKeys,
      halfCheckedKeys,
      allPermissions,
      handleShowChange,
      handleChangePassword,
      handleDisable,
      handleShowAdd,
      handleShowEdit,
      handleEditAccount,
      handleAddAccount,
      handleAddCancel,
      handleEditCancel,
      getPermissionAll,
      createItemTitleText,
      replacePermissionsTitle
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            roleId: ({ row }) => {
              return <div>{this.createItemTitleText(row.premissions)}</div>
            },
            status: ({ row }) => {
              return (
                <Space>
                  {row.deleteFlag === 1 ? (
                    <TypographyText type="danger">禁用</TypographyText>
                  ) : (
                    <TypographyText type="success">启用</TypographyText>
                  )}
                </Space>
              )
            },
            operation: ({ row }) => {
              return (
                <Space>
                  <Button
                    type="link"
                    size="small"
                    onClick={async () => {
                      await this.getPermissionAll()
                      this.handleShowEdit(row)
                    }}
                  >
                    编辑
                  </Button>
                  <Button
                    type="link"
                    size="small"
                    onClick={() => this.handleDisable(row)}
                  >
                    {row.deleteFlag === 1 ? '启用' : '禁用'}
                  </Button>
                  <Button
                    type="link"
                    size="small"
                    onClick={() => this.handleShowChange(row)}
                  >
                    修改密码
                  </Button>
                </Space>
              )
            },
            toolbarButtons: () => {
              return (
                <Button
                  type="primary"
                  onClick={async () => {
                    await this.getPermissionAll()
                    this.handleShowAdd()
                  }}
                >
                  新增管理
                </Button>
              )
            }
          }}
          {...this.tableConfig}
        />
        {/* 修改密码 */}
        <Modal
          v-model:visible={this.showChange}
          title="修改密码"
          onOk={this.handleChangePassword}
          destroyOnClose
          width={400}
        >
          <Input placeholder="输入新密码" v-model:value={this.newPassword} />
        </Modal>
        {/* 修改账号 */}
        <Modal
          v-model:visible={this.showEdit}
          title="编辑账号"
          onOk={() => {
            this.handleEditAccount()
          }}
          destroyOnClose
          onCancel={this.handleEditCancel}
        >
          <Form labelCol={this.labelCol} wrapperCol={this.wrapperCol}>
            <FormItem
              label="管理员姓名:"
              name="realName"
              {...this.editFormRef.validateInfos['realName']}
            >
              <Input
                placeholder="请输入管理员姓名"
                v-model:value={this.editFormState.realName}
                disabled
              />
            </FormItem>
            <FormItem
              label="管理员账号:"
              name="userName"
              {...this.editFormRef.validateInfos['userName']}
            >
              <Input
                placeholder="请输入管理员账号"
                v-model:value={this.editFormState.userName}
                disabled
              />
            </FormItem>
            <FormItem
              label="板块权限:"
              name="permissions"
              {...this.editFormRef.validateInfos['permissions']}
            >
              <Tree
                v-model:checkedKeys={this.checkedKeys}
                checkable
                replaceFields={{
                  children: 'children',
                  title: 'sourceName',
                  key: 'id'
                }}
                treeData={this.allPermissions}
                onCheck={(v, e) => {
                  this.halfCheckedKeys = e.halfCheckedKeys
                }}
              ></Tree>
            </FormItem>
          </Form>
        </Modal>
        {/* 新增账号 */}
        <Modal
          v-model:visible={this.showAdd}
          title="新增账号"
          onOk={() => {
            this.handleAddAccount()
          }}
          onCancel={this.handleAddCancel}
        >
          <Form labelCol={this.labelCol} wrapperCol={this.wrapperCol}>
            <FormItem
              label="管理员姓名:"
              name="realName"
              {...this.addFormRef.validateInfos['realName']}
            >
              <Input
                placeholder="请输入管理员姓名"
                v-model:value={this.addFormState.realName}
              />
            </FormItem>
            <FormItem
              label="管理员账号:"
              name="userName"
              {...this.addFormRef.validateInfos['userName']}
            >
              <Input
                placeholder="请输入管理员账号"
                v-model:value={this.addFormState.userName}
              />
            </FormItem>
            <FormItem
              label="板块权限:"
              name="permissions"
              {...this.addFormRef.validateInfos['permissions']}
            >
              <Tree
                v-model:checkedKeys={this.checkedKeys}
                checkable
                replaceFields={{
                  children: 'children',
                  title: 'sourceName',
                  key: 'id'
                }}
                treeData={this.allPermissions}
                onCheck={(v, e) => {
                  this.halfCheckedKeys = e.halfCheckedKeys
                }}
              ></Tree>
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
